﻿using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core;
using System;
using AutoMapper;
using Coldairarrow.Business.Cache;
using Coldairarrow.Entity.Base_bankcode;
using Coldairarrow.Entity.Base_leasesystem_accountrecharge;
using Coldairarrow.Entity.Base_leasesystem_car;
using Coldairarrow.Entity.Base_leasesystem_dictionary_types;
using Coldairarrow.Entity.Base_leasesystem_dictionary_values;
using Coldairarrow.Entity.Base_Leasesystem_equipment;
using Coldairarrow.Entity.Base_leasesystem_invoicedetail;
using Coldairarrow.Entity.Base_leasesystem_merchant;
using Coldairarrow.Entity.Base_leasesystem_serviceaccount;
using Coldairarrow.Entity.Base_leasesystem_transactionbatch;
using Coldairarrow.Entity.Base_leasesystem_transactionbatchsub;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.ViewModel;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Coldairarrow.Entity.Base_leasesystem_invoiceinformation;
//using Aop.Api.Request;

namespace Coldairarrow.Business.Base_Manage
{
    public class HomeBusiness : BaseBusiness<Base_User>, IHomeBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly IMapper _mapper;
        private readonly IBase_UserCache _base_UserCache;
        public HomeBusiness(IDbAccessor db, IOperator @operator, IMapper mapper, IBase_UserCache base_UserCache)
            : base(db)
        {
            _operator = @operator;
            _mapper = mapper;
            _base_UserCache = base_UserCache;
        }

        public async Task<string> SubmitLoginAsync(LoginInputDTO input)
        {
            input.password = input.password.ToMD5String();
            var theUser = await GetIQueryable()
                .Where(x => x.UserName == input.userName && x.Password == input.password)
                .FirstOrDefaultAsync();

            if (theUser.IsNullOrEmpty())
                throw new BusException("账号或密码不正确！");

            return theUser.Id;
        }

        public async Task ChangePwdAsync(ChangePwdInputDTO input)
        {
            var theUser = _operator.Property;
            if (theUser.Password != input.oldPwd?.ToMD5String())
                throw new BusException("原密码错误!");

            theUser.Password = input.newPwd.ToMD5String();
            await UpdateAsync(_mapper.Map<Base_User>(theUser));

            //更新缓存
            await _base_UserCache.UpdateCacheAsync(theUser.Id);
        }

        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public object GetMerchantInfo( PageInput<ConditionDTO> input)
        {
            var query1 = Db.GetIQueryable<leasesystem_merchant>().Where(a=>a.CheckStatus != 3).ToList();
            List<leasesystem_merchant> query = new List<leasesystem_merchant>();
            if (input.Search.Id.IsNullOrEmpty())
            {
                query = Db.GetIQueryable<leasesystem_merchant>().ToList();//客户列表  总数
            }
            else { 
                query = Db.GetIQueryable<leasesystem_merchant>().Where(a=>a.Id == input.Search.Id).ToList();//客户列表  总数
            }
                
            var rechargelist = Db.GetIQueryable<leasesystem_accountrecharge>().ToList();
            decimal? sumrecharge = rechargelist.Where(a => a.RechargeStatus == 1).Sum(a => a.RechargeAmount);//获取
            var batch = Db.GetIQueryable<leasesystem_transactionbatch>().ToList();

            //获取客户总余额
            decimal ? batchmoney = Db.GetIQueryable<leasesystem_transactionbatch>().Join(Db.GetIQueryable<leasesystem_transactionbatchsub>(), a => a.Id, b => b.TBID, (a, b) =>
            new {
                b.trxSts,
                b.PaymentOutAmount
            }).Where(a=>a.trxSts =="1" || a.trxSts == "2").Sum(a=>a.PaymentOutAmount);//查询状态为1 成功  2. 正在代发

            List<MerchantInfoModel> list = new List<MerchantInfoModel>();
           
            for (int i = 0; i < query.Count; i++)
                {
                    MerchantInfoModel model = new MerchantInfoModel();
                    model.Id = query[i].Id;
                    model.MerchantName = query[i].customerName;
                    model.rechargecount = rechargelist.Where(a => a.MID == query[i].Id).Count();
                    model.batchcount = batch.Where(a => a.MID == query[i].Id).Count();
                    //获取代发总金额   单个客户
                    decimal? singbatchmoney = Db.GetIQueryable<leasesystem_transactionbatch>().Where(a=>a.MID == query[i].Id).Join(Db.GetIQueryable<leasesystem_transactionbatchsub>(), a => a.Id, b => b.TBID, (a, b) =>
                    new {
                        b.trxSts,
                        b.PaymentOutAmount
                    }).Where(a => a.trxSts == "1" || a.trxSts == "2").Sum(a => a.PaymentOutAmount);//代发金额

                    model.money = rechargelist.Where(a => a.RechargeStatus == 1 && a.MID == query[i].Id).Sum(a => a.AccountAmount) - singbatchmoney;
                list.Add(model);
                }

            var result = new
            {
                Total = query1.Count() > 0 ? query1.Count() : 0,
                MerchantCount = query1.Count() > 0 ? query1.Count() : 0,//客户总数
                totalrecharge = sumrecharge > 0 ? sumrecharge : 0,//总充值金额
                totalaccountmoney = (sumrecharge - batchmoney) > 0 ? sumrecharge - batchmoney : 0,//总余额
                dataresult = list.Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows).Count() > 0 ? list.Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows) : null
            };
            return result;
        }

        /// <summary>
        /// 获取交易统计信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public object GetTran_statiscs(PageInput<ConditionDTO> input) 
        {
            var rechargeList = Db.GetIQueryable<leasesystem_accountrecharge>();//充值
            var batch = Db.GetIQueryable<leasesystem_transactionbatch>().ToList();//代发明细
            var Tran_count = rechargeList.Where(a => a.CreateTime.Month == int.Parse(input.Search.Id)).GroupBy(a => a.MID).Count();
            var rechargecount = rechargeList.Where(a => a.CreateTime.Month == int.Parse(input.Search.Id)).Count();//充值笔数
            var rechargeMoney = rechargeList.Where(a => a.CreateTime.Month == int.Parse(input.Search.Id)).Sum(a => a.RechargeAmount);//充值金额
            var batchcount = Db.GetIQueryable<leasesystem_transactionbatchsub>().Where(a => a.CreateTime.Value.Month == int.Parse(input.Search.Id)).Count();//代发笔数
            var batchMoney = Db.GetIQueryable<leasesystem_transactionbatchsub>().Where(a => a.CreateTime.Value.Month == int.Parse(input.Search.Id)).Sum(a => a.PaymentOutAmount);//代发金额

            List<Tran_statiscs> TranList = new List<Tran_statiscs>();
            var query1 = Db.GetIQueryable<leasesystem_merchant>().ToList();
            for (int i = 0; i < query1.Count; i++)
            {
                Tran_statiscs Tran = new Tran_statiscs();
                Tran.Id = query1[i].Id;
                Tran.MerchantName = query1[i].customerName;
                Tran.rechargemoney = rechargeList.Where(a => a.CreateTime.Month == int.Parse(input.Search.Id) && a.MID == query1[i].Id).Sum(a => a.RechargeAmount);//充值金额
                Tran.shimoney = Db.GetIQueryable<leasesystem_transactionbatch>().Where(a => a.MID == query1[i].Id).Join(Db.GetIQueryable<leasesystem_transactionbatchsub>(), a => a.Id, b => b.TBID, (a, b) =>
                       new {
                           b.trxSts,
                           b.PaymentOutAmount,
                           b.CreateTime
                       }).Where(a => a.trxSts == "1" && a.CreateTime.Value.Month == int.Parse(input.Search.Id)).Sum(a => a.PaymentOutAmount);//成功金额
                Tran.batchmoney = Db.GetIQueryable<leasesystem_transactionbatch>().Where(a => a.MID == query1[i].Id).Join(Db.GetIQueryable<leasesystem_transactionbatchsub>(), a => a.Id, b => b.TBID, (a, b) =>
                       new {
                           b.trxSts,
                           b.PaymentOutAmount,
                           b.CreateTime
                       }).Where(a => a.trxSts == "1" || a.trxSts == "2" && a.CreateTime.Value.Month == int.Parse(input.Search.Id))
                       .Sum(a => a.PaymentOutAmount);//总代发金额
                Tran.batchcount = Db.GetIQueryable<leasesystem_transactionbatch>().Where(a => a.MID == query1[i].Id).Join(Db.GetIQueryable<leasesystem_transactionbatchsub>(), a => a.Id, b => b.TBID, (a, b) =>
                       new
                       {
                           b.CreateTime
                       }).Where(a => a.CreateTime.Value.Month == int.Parse(input.Search.Id)).Count();//代发笔数
                Tran.money = Tran.rechargemoney - Tran.batchmoney;//余额
                TranList.Add(Tran);
            }

            var result = new {
                Total = query1.Count(),
                Tran_count = Tran_count,//交易客户数量
                rechargecount = rechargecount,//充值笔数
                rechargeMoney = rechargeMoney,//充值金额
                batchcount = batchcount,//代发笔数
                batchMoney = batchMoney,//代发金额
                result = TranList
            };
            return result;
        }

        
        public async Task<object> GetAccount_Merchant(string Id)
        {
            var userinfo = Db.GetEntity<Base_User>(Id);
            
            if (userinfo==null) {
                throw new BusException("无此客户信息！");
            }
            var Merchant = Db.GetEntity<leasesystem_merchant>(userinfo.brandId).CheckStatus != 3 ? Db.GetEntity<leasesystem_merchant>(userinfo.brandId):null;
            var invoice =await Db.GetIQueryable<leasesystem_invoiceinformation>().Where(a => a.MID == Merchant.Id).FirstOrDefaultAsync();
            if (Merchant == null)
            {
                invoice = null;
            }
            var result = new
            {
                Merchant = Merchant,
                invoice = invoice
            };
            return result;
        }

        public async Task<object> GetDic_type()
        {
            var query =await Db.GetIQueryable<leasesystem_dictionary_types>().Select(a => new
            {
                a.Id,
                a.name
            }).ToListAsync();
            return query;
        }

        public async Task<object> GetDic_value()
        {
            var query = await Db.GetIQueryable<leasesystem_dictionary_values>().Select(a => new
            {
                a.Id,
                a.name
            }).ToListAsync();
            return query;
        }

        public async Task<object> GetBank_Code()
        {
            var query = await Db.GetIQueryable<bankcode>().Select(a => new
            {
                a.Id,
                a.bankname,
                a.PayMaxAmount,
                a.DayPayMaxAmount
            }).ToArrayAsync();
            return query;
        }

        public async Task<object> GetServiceBank(PageInput<ConditionDTO> input)
        {
            var query = await Db.GetIQueryable<leasesystem_serviceaccount>().Where(a => a.SID == input.Search.Id).Select(a => new
            {
                a.Id,
                a.BankName,
                a.AcctNo
            }).ToListAsync();
            return query;
        }

        public async Task DeleteFile(string filepath)
        {
           
                DirectoryInfo info = new DirectoryInfo(filepath);
                // 去除文件夹的只读属性
                info.Attributes = FileAttributes.Normal & FileAttributes.Directory;
                // 去除文件的只读属性
                File.SetAttributes(filepath, FileAttributes.Normal);
                // 判断文件夹是否存在
                if (Directory.Exists(filepath))
                {
                    foreach (var file in Directory.GetFileSystemEntries(filepath))
                    {
                        if (File.Exists(file))
                        {
                            // 如果有子文件则删除子文件的所有文件
                            File.Delete(file);
                        }
                        else
                        {
                            // 循环递归删除子文件夹
                            DeleteFile(file);
                        }
                    }
                    // 删除已空文件夹(此步骤会删除指定目录的最底层文件夹，建议保留文件夹目录，此句注释)
                     Directory.Delete(filepath, true);
                }
        }

        public async Task<object> GetHomeData(PageInput<ConditionDTO> input,string userid)
        {
            var user = Db.GetEntity<Base_User>(userid);
           
            var Merchantcount =await Db.GetIQueryable<leasesystem_merchant>().CountAsync();
            //if (!user.brandId.IsNullOrEmpty()) {
            //    Merchantcount
            //}
            var carcount = await Db.GetIQueryable<leasesystem_car>().CountAsync();
            var devicecount = await Db.GetIQueryable<leasesystem_equipment>().CountAsync();
            //var batchsub = Db.GetIQueryable<leasesystem_transactionbatchsub>().Where(a=>a.trxSts == 1.ToString() || a.trxSts ==2.ToString());
            //var batchsubcount =await batchsub.CountAsync();
            //var batchtotalmoney = await batchsub.SumAsync(a=>a.PaymentOutAmount);

            var recharge = Db.GetIQueryable<leasesystem_accountrecharge>().Where(a=>a.RechargeStatus ==1 || a.RechargeStatus == 2);

            var rechargecount =await recharge.CountAsync();
            var rechargemoney = await recharge.SumAsync(a=>a.RechargeAmount);

            DateTime dt = DateTime.Now;  //当前时间  
            DateTime startWeek = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek.ToString("d")));  //本周周一  
            DateTime endWeek = startWeek.AddDays(6);  //本周周日
            


            DateTime startMonth = dt.AddDays(1 - dt.Day);  //本月月初  
            DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);  //本月月末  

            DateTime endYear = dt.AddYears(-6);  

            
            List<int> weekcount = new List<int>();
            List<decimal>  weekmoney = new List<decimal>();
            List<int> yearList = new List<int>();
            //周
            if (input.Search.Condition == "week")
            {
                for (int i = 0; i <= 6; i++)
                {
                    DateTime tempweek = startWeek.AddDays(i);
                    DateTime time2 = new DateTime(tempweek.Year, tempweek.Month, tempweek.Day);
                    DateTime time3 = tempweek.AddDays(i + 1);
                    DateTime time4 = new DateTime(time3.Year, time3.Month, time3.Day);

                    var weektemp = recharge.Where(a => a.CreateTime > time2 && a.CreateTime < time4);
                    weekcount.Add(weektemp.Count());
                    weekmoney.Add(weektemp.Sum(a => a.RechargeAmount));
                }
            }
            else if (input.Search.Condition == "month")
            {
                var monthtemp = recharge.OrderBy(a=>a.CreateTime.Month);
                for (int i = 0; i < 12; i++)
                {
                    var signmonth = monthtemp.Where(a => a.CreateTime.Month == i);
                    weekcount.Add(signmonth.Count());
                    weekmoney.Add(signmonth.Sum(a => a.RechargeAmount));
                }
            }
            else {
                for (int i = 5; i >=0; i--)
                {
                    var yeartemp = recharge.Where(a=>a.CreateTime.Year == dt.AddYears(-i).Year);
                    decimal money = yeartemp.Sum(a => a.RechargeAmount);
                    if (money>0) {
                        yearList.Add(dt.AddYears(-i).Year);
                        weekcount.Add(yeartemp.Count());
                        weekmoney.Add(money);
                    }
                    
                }
            }

            var result = new { 
                Merchantcount = Merchantcount,
                carcount = carcount,
                devicecount = devicecount,
                rechargecount = rechargecount,
                rechargemoney = rechargemoney,
                CountData = weekcount,
                MoneyData = weekmoney
            };
            return result;
        }

        public async Task SendMessage()
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "<AccessKeyId>", "<AccessSecret>");
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest
            {
                Method = MethodType.POST,
                Domain = "dysmsapi.aliyuncs.com",
                Version = "2017-05-25",
                Action = "SendMessageToGlobe"
            };
            // request.Protocol = ProtocolType.HTTPS;
            request.AddQueryParameters("To", "62123****8901");
            request.AddQueryParameters("PhoneNumber", "156****0987");
            // request.AddQueryParameters("From", "1234567890");
            request.AddQueryParameters("Message", "have a test.");
            // request.AddQueryParameters("Type", "OTP");
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                Console.WriteLine(response.Data);
            }
            catch (ServerException e)
            {
            }
        }
    }
}
